import Vue from 'vue';
import 'normalize.css/normalize.css';

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

import '@/styles/index.scss'; // global css
import components from '@/components';
import App from './App';
import api from './api';
import router from './router';
import store from './store';
import NProgress from 'nprogress'; // Progress 进度条
import 'nprogress/nprogress.css'; // Progress 进度条样式
import { getToken } from '@/utils/auth'; // 验权
import filters from '@/utils/filters'; // 过滤器
import '@/icons'; // icon
import mavonEditor from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';

// use
Vue.prototype.$API = api;
Vue.use(mavonEditor);
Vue.use(ElementUI, { size: 'small' });
Vue.config.productionTip = false;
// 注册全局组件
Object.keys(components).forEach(key => {
  const name = components[key].name;
  Vue.component(name, components[key]);
});
Object.keys(filters).forEach(k => Vue.filter(k, filters[k]));

const whiteList = ['/login']; // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (getToken()) {
    if (to.name !== 'login') {
      if (!store.getters.userInfo) {
        store.dispatch('fetchUserInfo').then(res => {
          const tree = res.data.powerTree;
          store.dispatch('generateRoutes', tree).then(() => {
            console.log(store.getters.extendRoutes);
            router.addRoutes(store.getters.extendRoutes); // 动态添加可访问路由表
            next({ ...to });
          });
        }).catch(() => {
          next({ path: '/login' });
        });
      } else {
        next();
      }
    } else {
      next('/buyphone');
      NProgress.done();
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next('/login');
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // 结束Progress
});

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');
